const CryptoJS = require('crypto-js/crypto-js')
// 默认的 KEY 与 iv 如果没有给
// const KEY = CryptoJS.enc.Utf8.parse("posDbvu+9y3JJk7upbGXCg==");//""中与后台一样  密码
const KEY = CryptoJS.enc.Utf8.parse('JGopQYcNKa1YHQGYUr$KJq=Q5pUpKaKY') //""中与后台一样  密码

// 加密算法
function Eecrypt(word, keyStr) {
    let key = KEY
    // let iv = IV

    if (keyStr) {
        key = CryptoJS.enc.Utf8.parse(keyStr)
        // iv = CryptoJS.enc.Utf8.parse(ivStr);
    }

    let srcs = CryptoJS.enc.Utf8.parse(word)
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {
        //   iv: IV,
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    })
    //   return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
    return CryptoJS.enc.Hex.stringify(encrypted.ciphertext)
}

/**
 * AES 解密 ：字符串 key iv  返回base64
 *
 */
function Decrypt(word, keyStr) {
    let key = KEY
    // let iv = IV

    if (keyStr) {
        key = CryptoJS.enc.Utf8.parse(keyStr)
        // iv = CryptoJS.enc.Utf8.parse(ivStr);
    }
    let encryptedHexStr = CryptoJS.enc.Hex.parse(word)
    let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr)

    var decrypt = CryptoJS.AES.decrypt(srcs, key, {
        //   iv: IV,
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    })

    var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
    return decryptedStr.toString()
}

module.exports = {Eecrypt,Decrypt}